<?php
/*会员管理控制器*/
namespace Admin\Controller;

class MemberController extends AdminController {

    /**
     * 主列表
     *会员查看
     */

    public function index()
    {
        /* 查询条件初始化 */
        $sear_val = I('sear_val');
        $map['status']  =   array('egt',0);
        if (is_numeric($sear_val)) {
            $map['tel'] = array('like', '%'.$sear_val.'%');
        } else {
            $map['name'] = array('like', '%'.(string)$sear_val.'%');
        }
        $map['isshow'] = 1;
        $list = $this->lists('treemember',$map);
        $this->assign('_list', $list);
        $this->display();

    }
    /**
     * 会员添加
     */
    public function add()
    {
        if (!$_POST) {
            $this->display();
        } else {
            $data = array('sex'=>I('user_sex'),
                                 'name'=>I('user_name'),
                                 'tel'=>I('user_tel'),
                                 'pernumber'=>I('user_pernumber'),
                                 'bankcode'=>I('user_bankcode'),
                                 'age'=>I('user_age'),
                                 'industry'=>I('user_industry'),
                                 'add_1'=>I('user_add_1'),
                                 'add_2'=>I('user_add_2'),
                                 'add_3'=>I('user_add_3'),
                                 'add_4'=>I('user_add_4'),
                                 'createtime'=>time(),
                                 'area_id'=>I('area'),
                                 'content'=>I('user_content'));
            /*开启事务*/
            M()->startTrans();
            $introducer_tel = I('user_introducer');
            $treemember = D('Treemember');
            $treemember_res = $treemember->where("tel = '$introducer_tel'")->find();
            $parentId = $treemember_res['id'];
            $treestruct = M('Treestruct');
            $treestruct_res = $treestruct->where("id='$parentId'")->find();
            if (!$treestruct_res) {
                M()->rollback();
                $this->error('请先验证介绍人手机号，没有介绍人默认添1');
            }
            $level = $treestruct_res['lvl'];
            $left = $treestruct_res['lft'];
            //将所有左值大于当前分类左值的分类左右值加2
            $res = $treestruct->where("lft>$left")->setInc('lft',2);
            if ($res === false) {
                M()->rollback();
                $this->error('添加失败！左值更新失败!');
            }            
            $res = $treestruct->where("lft>$left")->setInc('rgt',2);
            if ($res === false) {
                M()->rollback();
                $this->error('添加失败！右值更新失败!');
            }            
            $res = $treestruct->where("rgt>$left AND lft <= $left")->setInc('rgt',2);
            if ($res === false) {
                M()->rollback();
                $this->error('添加失败！右值更新失败!');
            }
            $treestruct_data['lft'] = $left + 1;
            $treestruct_data['rgt'] = $treestruct_data['lft'] + 1;
            $treestruct_data['pid'] = $parentId;
            $treestruct_data['lvl'] = $level + 1;
            $res = $treestruct->data($treestruct_data)->add();
            if (!$res) {
                M()->rollback();
            }
            $data['uid'] = $res;
            $data['id'] = $res;
            if (!$treemember->create($data)) {
                M()->rollback();
                $this->error($treemember->getError());
            }
            $res = $treemember->data($data)->add();
            if (!$res) {
                M()->rollback();
                $this->error('手机号不能重复!');
            }
            /**加分**/
            $add_int = D('Treemember')->addintegral($parentId,(int)I('user_bei'));
            if ($add_int  === false) {
                M()->rollback();
                $this->error('推荐人增加积分失败!');
            }
            /*提交事务*/
            M()->commit();
            $this->success('添加成功！',U('Member/index'));
        }
    }
    /**
     *添加会员验证
     * 验证手机号
     */
    public function member_check()
    {
        $tel = I('tel');
        if (is_numeric($tel)) {
            $member = D('Treemember')->check_tel($tel);
            if ($member) {
                $this->ajaxReturn(array('data'=>$member['name'],'reg'=>'1','info'=>'成功'),'json');
            } else {
                $this->ajaxReturn(array('reg'=>'2','info'=>'推荐人手机号不存在'),'json');
            }
        } else {
            $this->ajaxReturn(array('info'=>'请输入正确的手机号','reg'=>'3'),'json');
        }
        
    }
    /**
     * 删除会员操作
     */
    public function del()
    {
        $id = I('id');
        $treemember = D('Treemember');
        $res = $treemember->where('id='.$id)->setDec('isshow');
        if ($res == 1) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
    /**
     * 编辑用户信息
     */
    public function edit()
    {

    }
    /**
     * 会员结构查询
     */
    public function recom()
    {
        $this->display();
    }

    /**
     * 会员消费
     */
    public function consumption()
    {
        $sear_val = I('sear_val');
        $type = I('type');
        if ($type == 'recom'){
            $uid = I('id');
            $where = 'where consumption.uid='.(int)$uid;
        } else {
            if (is_numeric($sear_val)) {
                $where = "where tel like '%".$sear_val."%'";
            } else {
                $where = "where NAME like '%".$sear_val."%'";
            }
        }
        $list = M()->query('SELECT
                            consumption.id AS id,
                            consumption.uid AS uid,
                            consumption.createtime AS createtime,
                            consumption.integral AS integral,
                            consumption.content AS content,
                            treemember. NAME AS NAME,
                            treemember.tel AS tel,
                            treemember.pernumber AS pernumber
                        FROM
                            onethink_consumption consumption
                        JOIN onethink_treemember treemember ON consumption.uid = treemember.id '.$where);
        $count = M()->query('SELECT
                            COUNT(*)
                        FROM
                            onethink_consumption consumption
                        JOIN onethink_treemember treemember ON consumption.uid = treemember.id '.$where);
        $page = new \Think\Page($count['0']['COUNT(*)'],10);
        $page ->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        $this->assign('_page',$page->show());
        $this->assign('_list', $list);
        $this->display();
    }

    /**
     * 记录再消费
     */
    public function consumption_add()
    {
        if (IS_POST) {
            $info = $_POST;
            $treemember = D('Treemember');
            $treestruct = D('Treestruct');
            $integralchange = D('Integralchange');
            $district = M('district');
            $consumption = M('consumption');
            /**自己加分**/
            $treemember->add_integral($info['user_uid'],$info['user_integral']);
            $integralchange->data(array('uid'=>$info['user_uid'],
                                        'type'=>5,
                                        'integral'=>'+'.$info['user_integral'],
                                        'content'=>$info['user_content'],
                                        'changetime'=>time(),
                                        'changeuid'=>session('user_auth.uid')
                                ))->add();
            $consumption->data(array('c_uid'=>session('user_auth.uid'),
                                     'createtime'=>time(),
                                     'integral'=>$info['user_integral'],
                                     'content'=>$info['user_content'],
                                     'uid'=>$info['user_uid']
                                ))->add();
            /**上级加分**/
//            $pid = $treestruct->getpid($info['user_uid']);
//            if ($pid === false) {
//                $this->error('不能给总公司加分!');
//            }
//            $treemember->add_integral($pid,(int)$info['user_integral'] * C('integral_pay'));
//            $integralchange->data(array('uid'=>$pid,
//                                        'type'=>6,
//                                        'integral'=>'+'.$info['user_integral'] * C('integral_pay'),
//                                        'changetime'=>time(),
//                                        'changeuid'=>session('user_auth.uid')
//                            ))->add();
            /**区域代理加分**/
            $perinfo = $treemember->where(array('id'=>$info['user_uid']))->find();
            $area_info = $district->find($perinfo['area_id']);
            if (!$area_info['tel'] == null) {
                $treemember->where(array('tel'=>$area_info['tel']))->setInc('integral',(int)$info['user_integral'] * C('integral_agent'));
            }
            $area = $treemember->where(array('tel'=>$area_info['tel']))->find();
            $integralchange->data(array('uid'=>$area['id'],
                                        'type'=>7,
                                        'integral'=>'+'.$info['user_integral'] * C('integral_agent'),
                                        'changetime'=>time(),
                                        'changeuid'=>session('user_auth.uid')
                                ))->add();
        } else {
            $this->display();
        }
    }
    /**
     * 会员积分调整
     */
    public function integral()
    {
        if (IS_POST) {
            $treemember = D('Treemember');
            $integralchange = D('Integralchange');
            M()->startTrans();
            $uid = $treemember->field('id')->where(array('tel'=>I('user_tel')))->find();
            if (I('way') == '-') {
                $treemember_res = $treemember->where('uid='.$uid['id'])->setDec('integral',I('user_integral'));
                if ($treemember_res === false || $treemember_res === 0) {M()->rollback();}
            } else {
                $treemember_res = $treemember->where('uid='.$uid['id'])->setInc('integral',I('user_integral'));
                if ($treemember_res === false || $treemember_res === 0) {M()->rollback();}
            }
            $data = array(
                'uid' => $uid['id'],
                'type' =>'3',
                'integral'=>I('way').I('user_integral'),
                'content'=>I('user_content'),
                'changetime'=>time(),
                'changeuid'=>$_SESSION['onethink_admin']['user_auth']['uid']
            );
            $integralchange_res = $integralchange->data($data)->add();
            if ($integralchange_res === false) {
                M()->rollback();
            }
            M()->commit();
            $this->success('操作成功');
        } else {
            $this->display();
        }
    }
    /**
     * 验证手机 获取积分
     */
    public function integral_getinfo()
    {
        $tel = I('tel');
        $treemember = D('Treemember');
        $healthypic = D('healthypic');
        $info = $treemember->where(array('tel'=>$tel))->find();
        $img = $healthypic->where(array('u_id'=>$info['id']))->select();
        if ($info === false || empty($tel) || $info === null) {
            $this->ajaxReturn(array('reg'=>'2','info'=>'没有这个手机号'),'json');
        } else {
            $this->ajaxReturn(array('reg'=>'1','info'=>$info,'img'=>$img),'json');
        }
    }
    /**
     * 会员推荐
     */
    public function tuijian()
    {
        $this->display();
    }
    /**
     * 微信推荐会员显示
     */
    public function wechat_member()
    {
        /* 查询条件初始化 */
        $a = D('TreestructView');
        $b = M();
        $list = $b->query('SELECT m.name,
                            m.tel,
                            m.add_1,
                            m.add_2,
                            m.pernumber,
                            m.industry,
                            m.id,
                            s.pid,
                            (SELECT name FROM onethink_treemember WHERE id=s.pid) AS pname
                            FROM onethink_treemember m,onethink_treestruct s
                            WHERE m.id=s.id AND m.isshow=2');
        $wechat_member = D('Treemember');
        $count = D('Treemember')->where('isshow=2')->count();
        $page = new \Think\Page($count,10);
        /**查询内容**/
        $page ->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        $this->assign('_page',$page->show());
        $this->assign('_list', $list);
        $this->display();
    }
    /**
     * 验证通过
     */
    public function wechat_check()
    {
        $id = I('id');
        $treemember = D('Treemember');
        $res = $treemember->where('id='.$id)->setDec('isshow');
        M()->startTrans();
        $pid = D('Treestruct')->where('id='.$id)->find();
        $add_int = D('Treemember')->addintegral($pid['pid']);
        if ($add_int == false) {
            M()->rollback();
        }
        M()->commit();
        if ($res == 1) {
            $this->success('验证成功');
        } else {
            $this->error('验证失败');
        }
    }
    /**
     * 会员积分动态
     */
    public function integral_change()
    {
        /* 查询条件初始化 */
        $sear_val = I('sear_val');
        if ($_GET['type'] == 'recom') {
            $where['uid'] = $sear_val;
        } else {
            if (is_numeric($sear_val)) {
                $where['uid'] = array('like', '%'.$sear_val.'%');
            } else {
                $where['name'] = array('like', '%'.(string)$sear_val.'%');
            }
        }
        $integralchange = D('IntegralchangeView');
        $list = $integralchange->where($where)->select();
        foreach ($list as $k => $v) {
            switch ($v['type']) {
                case 1:
                    $list[$k]['type'] = '购物';
                    break;
                case 2:
                    $list[$k]['type'] = '提现';
                    break;
                case 3:
                    $list[$k]['type'] = '其他';
                    break;
                case 4:
                    $list[$k]['type'] = '推荐加分';
                    break;
                case 5:
                    $list[$k]['type'] = '再消费';
                    break;
                case 6:
                    $list[$k]['type'] = '下级消费';
                    break;
                case 7:
                    $list[$k]['type'] = '区域消费';
                    break;
                default:
                    $list[$k]['type'] = '其他';
                    break;
            }
        }
        $count = $integralchange->where($where)->count();
        $page = new \Think\Page($count,10);
        $page ->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        $this->assign('_page',$page->show());
        $this->assign('_list', $list);
        $this->display();    
       
    }

    /**
     * 健康档案添加
     */
    public function healthy_add()
    {
        if (IS_GET) {
            $id = I('get.id');
            if (!empty($id)) {
                $info = D('Treemember')->where(array('id'=>$id))->find();
                $img = M('healthypic')->where(array('u_id'=>$id,'isshow'=>1))->select();
                $this->assign('info',$info);
                $this->assign('img',$img);
                $this->display();
            } else {
                $this->display();
            }
        } elseif (IS_AJAX) {
            $info = $_POST;
            $treemember_data = $info;
            $treemember_data['sex'] = $info['user_sex'];
            if ($info['user_add_1'] != '') {
                $treemember_data['add_1'] = $info['user_add_1'];
            }
            if ($info['user_add_2'] != '') {
                $treemember_data['add_2'] = $info['user_add_2'];
            }
            if ($info['user_add_3'] != '') {
                $treemember_data['add_3'] = $info['user_add_3'];
            }
            if ($info['user_content'] != '') {
                $treemember_data['content'] = $info['user_content'];
            }
            unset($treemember_data['user_id']);
            unset($treemember_data['user_sex']);
            unset($treemember_data['user_add_1']);
            unset($treemember_data['user_add_2']);
            unset($treemember_data['user_add_3']);
            unset($treemember_data['user_content']);
            unset($treemember_data['healthy_content']);
            unset($treemember_data['pic_path']);
            $healthypic = M('healthypic');
            $res = D('Treemember')->data($treemember_data)->where(array('id'=>$info['user_id']))->save();
            if (!empty($info['pic_path'])) {
                $res2 = $healthypic->data(array('path'=>$info['pic_path'],'u_id'=>$info['user_id'],'content'=>$info['healthy_content']))->add();
            } else {
                $res2 = true;
            }
            if ($res !== false || $res2 !== false) {
                $this->success('编辑成功');
            } else {
                $this->error('编辑失败');
            }
        }
    }

    /**
     * 健康档案删除
     */
    public function healthy_del()
    {
        $id = I('id');
        $healthypic = M('healthypic');
        $res = $healthypic->where('id='.$id)->setDec('isshow');
        if ($res == 1) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
    public function test()
    {
        p(session('user_auth.uid'));
    }

    /**
     * 获取结构查看的JSON数据
     */
    public function echo_data()
    {
        $treemember = D('Treemember');
        if ($_POST['tel']) {
            $tel = I('tel');
            if (!$treemember->create(array('tel'=>$tel))) {
                $this->ajaxReturn(array('info'=>$treemember->getError(),'reg'=>2),'json');
            }
            $p_info = $treemember->where(array('tel'=>$tel))->find();
            if ($p_info['isshow'] != 1) {
                $this->ajaxReturn(array('info'=>'该会员未通过验证或该会员已被删除!','reg'=>2),'json');
            }
            session('json_data',$p_info['id']);
            $this->ajaxReturn(array('reg'=>1,'info'=>$p_info['id']),'json');
        } elseif ($_GET['id']) {
            $id = I('id');
            if ($id === '#') {
                $id = session('json_data');
            }
            $par_info = M()->query('SELECT
                                    s.id,
                                    s.lft,
                                    s.rgt,
                                    s.lvl,
                                    s.pid,
                                    m.name
                                FROM
                                    onethink_treestruct s,
                                    onethink_treemember m
                                WHERE
                                    s.id = m.id
                                AND s.id ='.$id);
            $json['0'] = array('id'=>$par_info['0']['id'],'text'=>$par_info['0']['name']);
            $children = M()->query('SELECT
                                    s.id,
                                    s.lft,
                                    s.rgt,
                                    s.lvl,
                                    s.pid,
                                    m.name
                                FROM
                                    onethink_treestruct s,
                                    onethink_treemember m
                                WHERE
                                m.isshow = 1
                                AND s.lft > ' .$par_info['0']['lft'] . '
                                AND s.rgt < ' . $par_info['0']['rgt'] . '
                                AND s.id = m.id
                                ORDER BY
                                    s.lft');
            if (empty($children)) {
                $json['0']['children'] = false;
                echo json_encode($json);
            } else {
                $children1 = array();
                $struct = D('Treestruct');
                foreach ($children as $k => $v) {
                    if ($v['lvl'] == $par_info['0']['lvl'] + 1) {
                        if ($struct->where(array('pid'=>$v['id']))->find() == null) {
                            array_push($children1,array('id'=>$v['id'],'text'=>$v['name'],'children'=>false));
                        } else {
                            array_push($children1,array('id'=>$v['id'],'text'=>$v['name'],'children'=>true));
                        }
                    }
                }
                $json['0']['children'] = $children1;
                echo json_encode($json);
            }
        }
    }
}